/**
 * Copyright (c) 2011-2012, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jfinal.ext.interceptor;

import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Const;
import com.jfinal.core.Controller;
import com.jfinal.ext.kit.SearchFilter;

/**
 * LogInterceptor.
 */
public class SearchSql implements Interceptor {
	private final String prefix = "search_";

	public void intercept(ActionInvocation ai) {
		Controller c = ai.getController();
		Map<String, Object> searchParams = getParametersStartingWith(c.getRequest(), prefix);
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		String whereSql = buildFilter(filters.values());
		c.setAttr(Const.SEARCH_SQL, whereSql);
		ai.invoke();
	}

	/**
	 * 取得带相同前缀的Request Parameters, copy from spring WebUtils.
	 * 
	 * 返回的结果的Parameter名已去除前缀.
	 */
	private Map<String, Object> getParametersStartingWith(
			HttpServletRequest request, String prefix) {
		Enumeration<String> paramNames = request.getParameterNames();
		Map<String, Object> params = new TreeMap<String, Object>();
		if (prefix == null) {
			prefix = "";
		}
		while (paramNames != null && paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			if ("".equals(prefix) || paramName.startsWith(prefix)) {
				String unprefixed = paramName.substring(prefix.length());
				String[] values = request.getParameterValues(paramName);
				if (values == null || values.length == 0) {
					// Do nothing, no values found at all.
				} else if (values.length > 1) {
					params.put(unprefixed, values);
				} else {
					params.put(unprefixed, values[0]);
				}
			}
		}
		return params;
	}

	/**
	 * 按属性条件列表创建查询字句
	 */
	private String buildFilter(final Collection<SearchFilter> filters) {
		StringBuilder sb = new StringBuilder();
		if (null != filters && filters.size() > 0) {
			for (SearchFilter filter : filters) {
				if (sb.length() > 0) {
					sb.append(" and ");
				}
				sb.append(filter.fieldName);
				switch (filter.operator) {
				case EQ:
					sb.append("='").append(filter.value).append("'");
					break;
				case LIKE:
					sb.append(" like ").append("'%" + filter.value + "%'");
					break;
				case GT:
					sb.append(">'").append(filter.value).append("'");
					break;
				case LT:
					sb.append("<'").append(filter.value).append("'");
					break;
				case GTE:
					sb.append(">='").append(filter.value).append("'");
					break;
				case LTE:
					sb.append("<='").append(filter.value).append("'");
					break;
				}
			}
		}
		return sb.toString();
	}
}